package org.tof.hotel.servlet;

import org.apache.log4j.Logger;
import org.tof.hotel.dao.AdministratorDaoImpl;
import org.tof.hotel.dto.AdministratorDTO;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;

public class CreateAdmin {

    static Logger logger = Logger.getLogger(CreateAdmin.class.getName());

    public void execute(HttpServletRequest request, HttpServletResponse response) throws IOException, ClassNotFoundException {

        try {
            request.setCharacterEncoding("UTF-8");
        } catch (UnsupportedEncodingException e) {
            logger.info(e.toString(), e);
        }

        AdministratorDTO dto = new AdministratorDTO(
                request.getParameter("firstName"),
                request.getParameter("lastName"),
                request.getParameter("phone"),
                request.getParameter("email"),
                request.getParameter("address"),
                request.getParameter("points").isEmpty() ? 0 : Integer.parseInt(request.getParameter("points")));
        AdministratorDaoImpl dao;

        ResultSet rs;
        try {
            dao = new AdministratorDaoImpl();
            dao.insert(dto);
            rs = dao.select(dto);

            ResultSetMetaData metaData = rs.getMetaData();
            int columnCount = metaData.getColumnCount();

            ArrayList<ArrayList<String>> admins = new ArrayList<ArrayList<String>>();
            ArrayList<String> admin = new ArrayList<String>();
            ArrayList<String> columnNames = new ArrayList<String>();

            //filling up columnNames list
            for (int i = 1; i <= columnCount; i++) {
                columnNames.add(metaData.getColumnName(i));
            }

            //filling up list of Administrators
            while (rs.next()) {
                admin.clear();
                for (int i = 1; i <= columnCount; i++) {
                    admin.add(rs.getString(i));
                }
                admins.add(admin);
            }

            request.setAttribute("admins", admins);
            request.setAttribute("columnNames", columnNames);
        } catch (SQLException e) {
            logger.warn(e.toString(), e);
            response.sendError(500, e.getMessage());
        }

    }
}
